# -*- coding:utf-8 -*-
from string import Template
import os
from service.ansible_operation import AnsibleApi

#加快ansible执行方法
def ansible_shll(host,module,args):
    run_ansible = AnsibleApi()
    tasks_list = []
    tasks_list.append(dict(action=dict(module=module, args=args)))
    run_ansible.runansible(host,tasks_list)

#模板渲染，保存到files目录中
def replaceConfig(file_path,data):
    with open(file_path,encoding='utf-8') as output:
        template_content = Template(output.read())
    template_content = template_content.safe_substitute(data)
    with open("module/nginx_config/files/" + data['agreement'] + '_' + data['serverName'] + '.conf', 'w+' , encoding='utf-8') as outfile:
        outfile.write(template_content)

#删除配置文件
def deleteConfig(data):
    os.remove("module/nginx_config/files/" + data['agreement'] + '_' + data['serverName'] + '.conf')


#判断协议，生成指定协议的配置文件
def productionTemplate(data):
    if data['agreement'] == "https":
        replaceConfig(file_path="module/nginx_config/template/" + data['agreement'] + ".conf", data=data)
    elif data['agreement'] == "http":
        replaceConfig(file_path="module/nginx_config/template/http.conf", data=data)
    else:
        print("【错误】yaml配置文件中agreement协议填写错误，只允许http/https")

def transferFiles(data):
    vhost_path = "/usr/local/nginx/conf/vhost"
    host = data['webGroup']
    args = "src=module/nginx_config/files/" + data['agreement'] + '_' + data['serverName'] + '.conf' \
        + ' ' + 'dest=' + vhost_path
    #拷贝文件
    ansible_shll(host=host,module="copy",args=args)
    ansible_shll(host=host,module='shell',args="nginx -t")
    ansible_shll(host=host,module='shell',args="nginx -s reload")



def run(value):
    for i in value['vhost']:
        productionTemplate(i)   #生成nginx配置文件
        transferFiles(i)        #拷贝文件到远程主机
        deleteConfig(i)   #删除本地临时配置文件